package au.com.centrumsystems.hudson.plugin.util.revision;

import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.logging.Logger;

public abstract class Extractor {

    private static final String NO_REVISION = "No Revision";
    private static final Logger LOGGER = Logger.getLogger(Extractor.class.getName());

    public static class Factory {

        public Extractor create(AbstractProject<?, ?> project) {
            String scmType = project.getScm().getType();
            if ("hudson.scm.SubversionSCM".equals(scmType)) {
                return new SvnExtractor();
            } else if ("hudson.plugins.git.GitSCM".equals(scmType)) {
                return new GitExtractor();
            } else if ("hudson.plugins.mercurial.MercurialSCM".equals(scmType)) {
                return new HgExtractor();
            }
            return new Extractor() {
                @Override
                protected String doExtract(AbstractBuild<?, ?> build) {
                    return Extractor.NO_REVISION;
                }
            };
        }
    } 

    public String extract(AbstractBuild<?, ?> build) {
        try {
            String revNo = doExtract(build);
            if (revNo == null) {
                return NO_REVISION;
            }
            return revNo;
        } catch (Exception e) {
            LOGGER.warning(e.toString());
        }
        return NO_REVISION;
    }

    protected abstract String doExtract(AbstractBuild<?, ?> build)
    throws MalformedURLException, IOException;

}

